package reflex;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: homechen
 * Date: 2024-03-12
 * Time: 8:23
 */
public class ReflexClass {
    // 创建对象
    public static void reflexnewInstance() {
        try {
            Class<?> classStudent = Student.class;
            Object object = classStudent.newInstance();
            Student student = (Student) object;
            System.out.println("获取对象：" + student);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 反射私有构造方法，屏蔽为公有
    public static void reflexPrivateConstructor() {
        try {
            Class<?> classStudent = Student.class;
            Constructor<?> declaredConstructor = classStudent.getDeclaredConstructor(int.class, String.class); // 传递构造方法的参数 确定哪个构造方法
            declaredConstructor.setAccessible(true);
            Object object = declaredConstructor.newInstance(22, "李四");
            Student student = (Student) object;
            System.out.println(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 反射私有属性
    public static void reflexPrivateField() {
        try {
            Class<?> classStudent = Student.class;
            Field field = classStudent.getDeclaredField("name");
            field.setAccessible(true);
            Object object = classStudent.newInstance();
            Student student = (Student) object;
            field.set(student, "小洪");

            String name = (String) field.get(student);
            System.out.println(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 反射私有方法
    public static void reflexPrivateMethod() {
        try {
            Class<?> classStudent = Student.class;
            Method method = classStudent.getDeclaredMethod("function", String.class);
            System.out.println("私有方法名为：" + method.getName());

            method.setAccessible(true);
            Object object = classStudent.newInstance();
            Student student = (Student) object;
            method.invoke(student, "给私有方法 function 传递的参数！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //reflexnewInstance();
        // reflexPrivateConstructor();
        // reflexPrivateField();
        reflexPrivateMethod();
    }
}
